﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Monarchy {
    public class ObjectFactory {

        private static Dictionary<string, object> _useContainer = new Dictionary<string, object>();
        private static Dictionary<string, object> UseContainer 
        {
            get { return _useContainer; }
            set { _useContainer = value; } 
        }

        public static object CreateObject(Type t) {
            if (UseContainer.ContainsKey(t.FullName)) return UseContainer[t.FullName];
            else {
                var ctors = t.GetConstructors();
                var args = new object[ctors[0].GetParameters().Length];
                Array.ForEach(ctors[0].GetParameters(), p => {
                    var parameterType = p.ParameterType;
                    var parameter = CreateObject(parameterType);

                    args[p.Position] = parameter;
                });

                return Activator.CreateInstance(t, args);
            }
        }

        public static void Use(object instance) {
            UseContainer.Add(instance.GetType().FullName, instance);
        }
    }
}
